#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AgriSmart.ErrorCode;
using ERP.ErrorCode;
using ERP.Infeartructure;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using REP.Domain.Entities;

namespace ERP.Api.Controllers
{
    /// <summary>
    /// 工艺路线接口
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class ProcessRoutesController : ControllerBase
    {
        private readonly ErpDbContext _db;
        public ProcessRoutesController(ErpDbContext db) => _db = db;

        public class ProcessRouteCreateDto
        {
            /// <summary>工艺路线编码</summary>
            public string? RouteCode { get; set; }
            /// <summary>工艺路线名称</summary>
            public string? RouteName { get; set; }
            /// <summary>标准总工时（小时）</summary>
            public decimal? StdTotalHours { get; set; }
            /// <summary>备注</summary>
            public string? Description { get; set; }
            /// <summary>操作人</summary>
            public string? Operator { get; set; }
        }

        /// <summary>
        /// 新增工艺路线，返回其 Id
        /// </summary>
        [HttpPost]
        public async Task<ActionResult<ApiResult<Guid?>>> Create([FromBody] ProcessRouteCreateDto dto)
        {
            var entity = new ProcessRoute
            {
                Id = Guid.NewGuid(),
                RouteCode = dto.RouteCode,
                RouteName = dto.RouteName,
                StdTotalHours = dto.StdTotalHours,
                Description = dto.Description,
                CreatedAt = DateTime.UtcNow,
                CreatedBy = dto.Operator
            };

            await _db.ProcessRoutes!.AddAsync(entity);
            await _db.SaveChangesAsync();

            return new ApiResult<Guid?>
            {
                Code = BaseEnums.Success,
                Msg = "创建成功",
                Data = entity.Id
            };
        }

        /// <summary>
        /// 分页查询工艺路线列表
        /// </summary>
        [HttpGet]
        public async Task<IActionResult> List([FromQuery] string? kw, [FromQuery] int page = 1, [FromQuery] int pageSize = 10)
        {
            if (page <= 0) page = 1;
            if (pageSize <= 0) pageSize = 10;

            var q = _db.ProcessRoutes!.AsNoTracking().AsQueryable();
            if (!string.IsNullOrWhiteSpace(kw))
            {
                var k = kw.Trim();
                q = q.Where(x => (x.RouteCode ?? "").Contains(k) || (x.RouteName ?? "").Contains(k));
            }

            var total = await q.CountAsync();
            var items = await q
                .OrderByDescending(x => x.CreatedAt)
                .Skip((page - 1) * pageSize)
                .Take(pageSize)
                .Select(x => new
                {
                    id = x.Id,
                    flowNo = x.RouteCode,
                    name = x.RouteName,
                    stepCount = x.StepCount ?? 0
                })
                .ToListAsync();

            return Ok(new { total, items });
        }
    }
}
